package com.tencent.wuyanzu.whattoeat.util;

/**
 * Created by bleuesprit on 2016/7/24.
 */

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.tencent.wuyanzu.whattoeat.R;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Objects;

/**
 * LruCache的流程分析:
 * 我们从第一次进入应用的情况下开始
 * 1 依据图片的Url从LruCache缓存中取图片.
 *   若图片存在缓存中,则显示该图片;否则显示默认图片
 * 2 因为是第一次进入该界面所以会执行:
 *   loadBitmaps(firstVisibleItem, visibleItemCount);
 *   我们从loadBitmaps()方法作为切入点,继续往下梳理
 * 3 尝试从LruCache缓存中取图片.如果在显示即可,否则进入4
 * 4 开启一个异步任务下载图片.下载完成后显示图片,并且将
 *   该图片存入LruCache缓存中
 *
 * 在停止滑动时,会调用loadBitmaps(firstVisibleItem, visibleItemCount)
 * 情况与上类似
 */
@SuppressLint("NewApi")
public class GridViewImageAdapter extends ArrayAdapter<String> {

    private GridView mGridView;
    private String mLrus[];
    //记录所有正在下载或等待下载的任务
    private HashSet<DownloadBitmapAsyncTask> mDownloadBitmapAsyncTaskHashSet;


    public GridViewImageAdapter(Context context, int textViewResourceId, String[] objects, GridView gridView) {
        super(context, textViewResourceId, objects);
        mLrus=objects;
        mGridView = gridView;
        mDownloadBitmapAsyncTaskHashSet = new HashSet<DownloadBitmapAsyncTask>();
        loadBitmaps(9);


    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String url = getItem(position);
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(R.layout.init_eat_fooditem, null);
        } else {
            view = convertView;
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.init_eat_foodImage);
        //为该ImageView设置一个Tag,防止图片错位
        imageView.setTag(url);
        //为该ImageView设置显示的图片

        imageView.setImageResource(R.drawable.cai);
        return view;
    }





    /**
     * 为GridView的item加载图片
     *
     *
     * @param visibleItemCount
     * GridView中可见的图片的数量
     *
     */
    private void loadBitmaps(int visibleItemCount) {
        try {
            for (int i = 0; i < visibleItemCount; i++) {
                String imageUrl = mLrus[i];
                DownloadBitmapAsyncTask downloadBitmapAsyncTask = new DownloadBitmapAsyncTask();
                mDownloadBitmapAsyncTaskHashSet.add(downloadBitmapAsyncTask);
                downloadBitmapAsyncTask.execute(imageUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消所有正在下载或等待下载的任务
     */
    public void cancelAllTasks() {
        if (mDownloadBitmapAsyncTaskHashSet != null) {
            for (DownloadBitmapAsyncTask task : mDownloadBitmapAsyncTaskHashSet) {
                task.cancel(false);
            }
        }
    }

    /**
     * 下载图片的异步任务
     */
    class DownloadBitmapAsyncTask extends AsyncTask<Object, Void, Bitmap> {
        private String imageUrl;
        @Override
        protected Bitmap doInBackground(Object... params) {
            imageUrl = (String) params[0];
            Bitmap bitmap = downloadBitmap((String)params[0]);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //下载完成后,找到其对应的ImageView显示图片
            ImageView imageView = (ImageView) mGridView.findViewWithTag(imageUrl);
            if (imageView != null && bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            mDownloadBitmapAsyncTaskHashSet.remove(this);
        }
    }

    // 获取Bitmap
    private Bitmap downloadBitmap(String imageUrl) {
        Bitmap bitmap = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(imageUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setConnectTimeout(5 * 1000);
            httpURLConnection.setReadTimeout(10 * 1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();
            httpURLConnection.getResponseMessage();
            Log.d("netword","httpURL state"+httpURLConnection.getResponseMessage());
            InputStream inputStream=httpURLConnection.getInputStream();
            //byte []buffer=new byte[10];
           // inputStream.read(buffer);
            if(inputStream==null)
            {
                Log.d("netword","inputis nullll");
            }
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return bitmap;
    }

}
